﻿// <copyright file="ModemTelegram.cs" company="Hallvard Korsgaard">
//  Microsoft Public License (Ms-PL). See license details here: http://enoceannet.codeplex.com/license
// </copyright>
// <author>Hallvard Korsgaard</author> 

namespace EnOcean.Radio.Modem
{
  using System;

  /// <summary>
  /// Represents a 6 byte modem telegram (ORG = 0x0A).
  /// </summary>
  [Serializable]
  public class ModemTelegram : RadioTelegram
  {
    /// <summary>
    /// Variable for the RecipientId property.
    /// </summary>
    private int recipientId;

    /// <summary>
    ///  Initializes a new instance of the ModemTelegram class.
    /// </summary>
    public ModemTelegram()
    {
      this.TelegramType = TelegramType.TransmitRadioTelegram;
    }

    /// <summary>
    /// Gets or sets the 16 bit modem ID of the receiving modem. The ID must be in the range 0 to 0xffff inclusive.
    /// </summary>
    public int RecipientId
    {
      get
      {
        return this.recipientId;
      }

      set
      {
        if (value >= 0x0 && value <= 0xffff)
        {
          this.recipientId = value;
        }
        else
        {
          throw new ArgumentOutOfRangeException("RecipientId", "must be a 16 bit value in the range 0x0 to 0xffff inclusive");
        }
      }
    }

    /// <summary>
    /// Gets or sets data byte 0.
    /// </summary>
    public byte Data0
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets data byte 1.
    /// </summary>
    public byte Data1
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets data byte 2.
    /// </summary>
    public byte Data2
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets data byte 3.
    /// </summary>
    public byte Data3
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets data byte 4.
    /// </summary>
    public byte Data4
    {
      get;
      set;
    }

    /// <summary>
    /// Gets or sets data byte 5.
    /// </summary>
    public byte Data5
    {
      get;
      set;
    }

    /// <summary>
    /// Creates the byte format of the message.
    /// </summary>
    /// <param name="message">A byte array of length 14 to hold the message contents.</param>
    protected internal override void CreateMessage(byte[] message)
    {
      base.CreateMessage(message);
      message[3] = (byte)Org.Modem; // Org
      message[4] = this.Data5; // Data 5
      message[5] = this.Data4; // Data 4
      message[6] = this.Data3; // Data 3
      message[7] = this.Data2; // Data 2
      message[8] = this.Data1; // Data 1
      message[9] = this.Data0; // Data 0
      message[10] = (byte)(this.recipientId >> 8); // Modem Id 1
      message[11] = (byte)(this.recipientId & 0xff); // Modem Id 0
      message[12] = this.RepeatCounter; // Status
    }
  }
}
